package com.tao.plan.common.task;


import com.tao.plan.common.utils.DateUtil;
import com.tao.plan.common.utils.EmailUtil;
import com.tao.plan.domain.pojo.*;
import com.tao.plan.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 计划定时推送,定时任务
 */
@Component
public class PushTask {
	@Autowired
	private EmailUtil emailUtil;
	@Autowired
	private PUserService userService;
	@Autowired
	private PCommonPlanService commonPlanService;
	@Autowired
	private PCountPlanService countPlanService;
	@Autowired
	private PMemoryDayService memoryDayService;
	@Autowired
	private PCountDownDayService countDownDayService;
	@Scheduled(cron = "0 30 8 * * ?")
	public void planPush(){
		// 可能需要查询一下, 需要的是对每个人都要推送
		List<PUser> users = userService.list();
		for (PUser user : users) {
			// 每一个用户
			Long userId = user.getId();
			Integer isPush = user.getIsPush();
			String email = user.getEmail();
			if(isPush == null || isPush == 0){
				continue;
			}
			// 学习任务
			List<PCommonPlan> commonPlans = commonPlanService.listByStatus(0,userId);
			// 计数任务
			List<PCountPlan> countPlans = countPlanService.listByStatus(0, userId);
			// 需要推送
			String content = emailUtil.readPlanHtmlTemplate("/template/emailPlan.html", commonPlans, countPlans);
			emailUtil.sendHtmlMail(email,"计划推送",content);
		}
	}


	/**
	 * 纪念日推送
	 */
	@Scheduled(cron = "0 30 8 * * ?")
//	@Scheduled(cron = "*/5 * * * * *")
	public void memoryPush(){
		// 可能需要查询一下, 需要的是对每个人都要推送
		// 获取今日的日历, 公历和农历
		List<PUser> users = userService.list();
		for (PUser user : users) {
			// 每一个用户
			Long userId = user.getId();
			Integer isPush = user.getIsPush();
			String email = user.getEmail();
			if(isPush == null || isPush == 0){
				continue;
			}
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			LocalDate calendar = LocalDate.now();
			LocalDate lunar = DateUtil.convertLunarToSolar(calendar);
			List<PMemoryDay> memoryDays = memoryDayService.listByDay(lunar.format(formatter),calendar.format(formatter),userId);
			List<PCountDownDay> countDownDays = countDownDayService.listByDateTime(0, userId);
			// 需要推送
			String content = emailUtil.readMemoryDayHtmlTemplate("/template/memoryDay.html", memoryDays, countDownDays);
			emailUtil.sendHtmlMail(email,"纪念日和倒计日",content);
		}
	}
}
